<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="1400px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleDialogClose"
  >
    <div class="project-form-container">
      <!-- 工程项目基本信息 -->
      <div class="form-section">
        <h3>工程项目基本信息</h3>
        <el-form ref="basicForm" :model="form" :rules="rules" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="工程项目名称" prop="projectName">
                <el-input v-model="form.projectName" placeholder="请输入工程项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="立项审批单位" prop="approvalAuthority">
                <el-input v-model="form.approvalAuthority" placeholder="请输入立项审批单位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="立项批复时间" prop="approvalDate">
                <el-input v-model="form.approvalDate" placeholder="请输入立项批复时间，如：2023年12月1日" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="初设批复时间" prop="preliminaryDesignDate">
                <el-input v-model="form.preliminaryDesignDate" placeholder="请输入初设批复时间，如：2023年12月1日" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="立项批复文件" prop="approvalDocument">
                <el-input
                  v-model="form.approvalDocument"
                  type="textarea"
                  :rows="3"
                  resize="vertical"
                  placeholder="请输入立项批复文件"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="初设批复文件" prop="preliminaryDesignDocument">
                <el-input
                  v-model="form.preliminaryDesignDocument"
                  type="textarea"
                  :rows="3"
                  resize="vertical"
                  placeholder="请输入初设批复文件"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="批复建设内容" prop="approvedConstructionContent">
                <el-input
                  v-model="form.approvedConstructionContent"
                  type="textarea"
                  :rows="4"
                  resize="vertical"
                  placeholder="请输入批复建设内容"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="批复概算(万元)" prop="approvedBudget">
                <el-input v-model="form.approvedBudget" placeholder="请输入批复概算（万元）" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 采购相关信息 -->
      <div class="form-section">
        <h3>采购相关信息</h3>
        <el-form :model="form" :rules="rules" ref="procurementForm" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购项目名称" prop="procurementProjectName">
                <el-input v-model="form.procurementProjectName" placeholder="请输入采购项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类别" prop="procurementCategory">
                <el-input v-model="form.procurementCategory" placeholder="例如：服务/货物/工程" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="采购内容" prop="procurementContent">
                <el-input
                  v-model="form.procurementContent"
                  type="textarea"
                  :rows="4"
                  resize="vertical"
                  placeholder="请输入采购内容"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="采购方式" prop="procurementMethod">
                <el-input v-model="form.procurementMethod" placeholder="例如：公开招标、竞争性谈判" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购代理机构" prop="procurementAgent">
                <el-input v-model="form.procurementAgent" placeholder="请输入采购代理机构" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="公告时间" prop="announcementTime">
                <el-input v-model="form.announcementTime" placeholder="请输入公告时间，如：2023年12月1日" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公告平台" prop="announcementPlatform">
                <el-input v-model="form.announcementPlatform" placeholder="请输入公告平台" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="送标人及联系方式" prop="bidderContactInfo">
                <el-input v-model="form.bidderContactInfo" placeholder="请输入送标人及联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参投单位" prop="biddingParticipants">
                <el-input
                  v-model="form.biddingParticipants"
                  type="textarea"
                  :rows="3"
                  placeholder="每行一个单位"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="中标单位" prop="winningBidder">
                <el-input v-model="form.winningBidder" placeholder="请输入中标单位" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开评审地点" prop="reviewLocation">
                <el-input v-model="form.reviewLocation" placeholder="请输入开评审地点" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="评审时间" prop="reviewTime">
                <el-input v-model="form.reviewTime" placeholder="请输入评审时间，如：2023年12月1日" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业主代表" prop="ownerRepresentative">
                <el-input v-model="form.ownerRepresentative" placeholder="请输入业主代表" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="参评业主代表联系方式" prop="ownerRepresentativeContact">
                <el-input v-model="form.ownerRepresentativeContact" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中标公示时间" prop="winningAnnouncementTime">
                <el-input v-model="form.winningAnnouncementTime" placeholder="请输入中标公示时间，如：2023年12月4日至2023年12月7日" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="公示平台" prop="winningAnnouncementPlatform">
                <el-input v-model="form.winningAnnouncementPlatform" placeholder="请输入公示平台" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中标金额(万元)" prop="winningBidAmount">
                <el-input v-model="form.winningBidAmount" placeholder="请输入中标金额" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="结算金额(万元)" prop="settlementAmount">
                <el-input v-model="form.settlementAmount" placeholder="请输入结算金额" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 合同信息 -->
      <div class="form-section">
        <h3>合同信息</h3>
        <el-form :model="form" :rules="rules" ref="contractForm" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="form.contractName" placeholder="请输入合同名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同号" prop="contractNumber">
                <el-input v-model="form.contractNumber" placeholder="请输入合同号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="合同主要内容" prop="contractContent">
                <el-input
                  v-model="form.contractContent"
                  type="textarea"
                  :rows="4"
                  resize="vertical"
                  placeholder="请输入合同主要内容"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="合同谈判日期" prop="negotiationDate">
                <el-input v-model="form.negotiationDate" placeholder="请输入合同谈判日期，如：2023年12月1日" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同签订日期" prop="contractSignDate">
                <el-input v-model="form.contractSignDate" placeholder="请输入合同签订日期，如：2023年12月1日" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="合同金额(万元)" prop="contractAmount">
                <el-input v-model="form.contractAmount" placeholder="请输入合同金额" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="甲方合同签署代表" prop="partyASignatory">
                <el-input v-model="form.partyASignatory" placeholder="请输入甲方签署代表" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="乙方合同签署代表" prop="partyBSignatory">
                <el-input v-model="form.partyBSignatory" placeholder="请输入乙方签署代表" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 项目管理与执行 -->
      <div class="form-section">
        <h3>项目管理与执行</h3>
        <el-form :model="form" :rules="rules" ref="managementForm" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目负责人" prop="projectManager">
                <el-input v-model="form.projectManager" placeholder="请输入项目负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="甲方现场负责人" prop="siteRepresentativePartyA">
                <el-input v-model="form.siteRepresentativePartyA" placeholder="请输入甲方现场负责人或代表" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="甲方经办人及联系电话" prop="handlerPartyA">
                <el-input v-model="form.handlerPartyA" placeholder="请输入甲方经办人及联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="乙方经办人及联系电话" prop="handlerPartyB">
                <el-input v-model="form.handlerPartyB" placeholder="请输入乙方经办人及联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 财务决算 -->
      <div class="form-section">
        <h3>财务决算</h3>
        <el-form :model="form" :rules="rules" ref="financeForm" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="最终决算金额(万元)" prop="finalSettlementAmount">
                <el-input v-model="form.finalSettlementAmount" placeholder="请输入最终决算金额" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否完成财务审计" prop="isFinancialAuditCompleted">
                <el-radio-group v-model="form.isFinancialAuditCompleted">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否进行财务评审" prop="isFinancialReviewCompleted">
                <el-radio-group v-model="form.isFinancialReviewCompleted">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 审核 -->
      <div class="form-section">
        <h3>审核意见</h3>
        <el-form :model="form" :rules="rules" ref="reviewForm" label-width="200px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="审核状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio label="-1">未处理</el-radio>
                  <el-radio label="0">作废</el-radio>
                  <el-radio label="1">审核通过</el-radio>
                  <el-radio label="2">预留</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="审核意见" prop="comment">
                <el-input
                  v-model="form.comment"
                  type="textarea"
                  :rows="4"
                  resize="vertical"
                  placeholder="审核意见"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </div>

    <!-- 操作按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addProject, updateProject } from '@/api/projectManager/project';
import { deepClone } from '@/utils';

export default {
  name: 'ProjectCreate',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      rules: {
        // 只保留两个必填字段
        projectName: [{ required: true, message: '工程项目名称不能为空', trigger: 'blur' }],
        procurementProjectName: [{ required: true, message: '采购项目名称不能为空', trigger: 'blur' }]
      },
      submitLoading: false
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    title() {
      return this.isEdit ? '修改工程项目' : '新增工程项目';
    }
  },
  watch: {
    data: {
      handler(val) {
        this.form = val ? deepClone(val) : {};
      },
      immediate: true
    }
  },
  methods: {
    // 检查表单是否有未保存的数据
    hasUnsavedData() {
      // 检查form是否有任何有意义的输入
      if (!this.form || typeof this.form !== 'object') return false;
      
      // 检查是否有任何非空值
      return Object.values(this.form).some(value => {
        if (value === null || value === undefined) return false;
        if (typeof value === 'string') {
          return value.trim() !== '';
        }
        return true;
      });
    },
    
    // 处理弹窗原生关闭事件（右上角X按钮）- 直接关闭
    handleDialogClose() {
      this.cancel();
    },
    
    // 处理关闭弹窗（取消按钮）- 有确认提示
    handleClose() {
      console.log('handleClose被调用');
      const hasData = this.hasUnsavedData();
      console.log('是否有未保存数据:', hasData);
      
      if (hasData) {
        console.log('显示确认对话框');
        this.$confirm('您有未保存的数据，确定要关闭吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户确认关闭');
          this.cancel();
        }).catch(() => {
          console.log('用户取消关闭');
          // 用户取消关闭，保持弹窗打开
        });
      } else {
        console.log('没有未保存数据，直接关闭');
        this.cancel();
      }
    },
    
    // 处理取消按钮点击
    handleCancel() {
      this.handleClose();
    },
    
    cancel() {
      // 重置所有表单
      if (this.$refs.basicForm) this.$refs.basicForm.resetFields();
      if (this.$refs.procurementForm) this.$refs.procurementForm.resetFields();
      if (this.$refs.contractForm) this.$refs.contractForm.resetFields();
      if (this.$refs.managementForm) this.$refs.managementForm.resetFields();
      if (this.$refs.financeForm) this.$refs.financeForm.resetFields();
      if (this.$refs.reviewForm) this.$refs.reviewForm.resetFields();
      
      this.submitLoading = false;
      this.$emit('update:visible', false);
    },
    submitForm() {
      // 检查必填表单是否存在
      if (!this.$refs.basicForm || !this.$refs.procurementForm) {
        console.error('表单引用不存在');
        this.$message.error('表单加载错误，请刷新页面重试');
        return;
      }
      
      // 验证包含必填字段的表单
      Promise.all([
        this.$refs.basicForm.validate(),
        this.$refs.procurementForm.validate()
      ]).then(() => {
        // 所有必填表单验证通过
        
        this.submitLoading = true;
        const loading = this.$loading({ text: '正在提交...' });
        const request = this.isEdit ? updateProject(this.form) : addProject(this.form);
        request
          .then(() => {
            this.$message.success(this.isEdit ? '修改成功' : '新增成功');
            this.$emit('submit', this.form);
            this.$emit('update:visible', false);
          })
          .catch((error) => {
            console.error('提交失败:', error);
            this.$message.error(this.isEdit ? '修改失败' : '新增失败');
          })
          .finally(() => {
            loading.close();
            this.submitLoading = false;
          });
      }).catch((error) => {
        // 验证失败，不执行提交
        console.error('表单验证失败:', error);
        this.$message.error('请填写必填字段');
      });
    }
  }
};
</script>

<style scoped>
.project-form-container {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.form-section {
  margin-bottom: 30px;
  border-bottom: 1px dashed #ddd;
  padding-bottom: 20px;
}

.form-section h3 {
  margin-bottom: 20px;
  color: #1890ff;
  font-size: 16px;
  font-weight: 600;
}

.el-row {
  margin-bottom: 16px;
}

.el-form-item {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}
</style>
